<!--
 * @Author: XieQiu 雪球
 * @Date: 2021-05-10 15:07:49
 * @LastEditTime: 2024-05-11 11:54:04
 * @LastEditors: Please set LastEditors
 * @Description: 设施划分管理页面 字段未改
-->
<template>
  <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar
        :page-no="47"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :has-cancel="false"
        :has-save="false"
        :has-del="false"
        :has-edit="false"
        :save-active="saveActive"
        @add="add"
        @cancel="cancel('formData')"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:tab-select>
      <SelectButton @topitemtype="topitemtype" />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <!-- <div class="pag"> -->
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 3.125rem)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="facilityTypeName" label="设施类型" />
        <el-table-column prop="facilityNo" label="设施编号" />
        <el-table-column prop="facilityName" label="设施名称" min-width="100" />
        <el-table-column prop="plantingTypeName" label="主要种养品种">
          <template v-if="scope.row.facilityNo" slot-scope="scope">
            <div v-if="scope.row.plantingTypeName">{{ scope.row.plantingTypeName }}</div>
            <div v-if="!scope.row.plantingTypeName">——</div>
            <!-- {{ scope.row.facilityCost }} 元 -->
          </template>
        </el-table-column>
        <el-table-column label="设施面积">
          <template slot-scope="scope">{{ scope.row.scope }} {{ unitname(scope.row.unitNo) }}</template>
        </el-table-column>
        <el-table-column prop="lesseeName" label="承租户">
          <template v-if="scope.row.facilityNo" slot-scope="scope">
            <div v-if="scope.row.lesseeName">{{ scope.row.lesseeName }}</div>
            <div v-if="!scope.row.lesseeName">——</div>
          </template>
        </el-table-column>
        <el-table-column prop="facilityCost" label="设施造价">
          <template v-if="scope.row.facilityNo" slot-scope="scope">
            <div v-if="scope.row.facilityCost">{{ scope.row.facilityCost }} 元</div>
            <div v-if="!scope.row.facilityCost">——</div>
            <!-- {{ scope.row.facilityCost }} 元 -->
          </template>
        </el-table-column>
        <el-table-column prop="facilityRent" label="设施租金">
          <template v-if="scope.row.facilityNo" slot-scope="scope">
            <div v-if="scope.row.facilityRent">{{ scope.row.facilityRent }} 元</div>
            <div v-if="!scope.row.facilityRent">——</div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="设施位置" min-width="100">
          <template v-if="scope.row.facilityNo" slot-scope="scope">
            <div v-if="scope.row.address">{{ scope.row.address }}</div>
            <div v-if="!scope.row.address">——</div>
            <!-- {{ scope.row.facilityCost }} 元 -->
          </template>
        </el-table-column>
        <!-- <el-table-column label="经纬度" min-width="130">
            <template
              v-if="scope.row.axisY || scope.row.axisX"
              slot-scope="scope"
            >
              {{ scope.row.axisY }} - {{ scope.row.axisX }}
            </template>
        </el-table-column>-->
        <el-table-column v-if="!topitemtypeid" prop="buildTime" label="建立时间" />
        <el-table-column v-if="topitemtypeid" prop="cancelTime" label="作废日期" />

        <el-table-column label="是否历史设施" min-width="105">
          <template v-if="scope.row.facilityNo" slot-scope="scope">
            <span>
              <!-- :disabled="topitemtypeid === 1 ? false : true" -->
              <el-switch
                v-model="scope.row.facilityStatus"
                :active-value="true"
                :inactive-value="false"
                @change="faciStatus(scope.row)"
              />
            </span>
          </template>
        </el-table-column>
        <el-table-column v-if="topitemtypeid==false" width="120" label="操作">
          <template v-if="scope.row.facilityNo" slot-scope="scope">
            <el-button
              v-if="judgePermission(47, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="handleEdit(scope.row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <!-- <el-button v-if="judgePermission(47, 'delete')" class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete(scope.row)"><i class="el-icon-delete"></i> 删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <!-- </div> -->
      <el-dialog
        :title="titleText + '设施'"
        class="formData"
        :visible.sync="dialogFormVisible"
        width="50%"
        top="5vh"
        :before-close="handleClose"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="农业类型:" prop="farmingTypeNo" class="w50p">
            <el-select
              v-model="formData.farmingTypeNo"
              :disabled="!canInput"
              clearable
              filterable
              @change="farmingType"
            >
              <el-option
                v-for="item in Baselist"
                :key="item.farmingTypeNo"
                :label="item.farmingTypeName"
                :value="item.farmingTypeNo"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="承租户:" prop="lesseeNo" class="w50p">
            <el-select
              v-model="formData.lesseeNo"
              clearable
              :disabled="!canInput"
              placeholder="请选择承租户"
            >
              <el-option
                v-for="(item, index) in lesseeList"
                :key="index"
                :label="item.lesseeName"
                :value="item.lesseeNo"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="设施类型:" prop="facilityTypeNo" class="w50p">
            <el-select
              v-model="formData.facilityTypeNo"
              :disabled="!canInput"
              clearable
              filterable
              @change="facilityCategory"
            >
              <el-option
                v-for="item in facilityTypeList"
                :key="item.facilityTypeNo"
                :label="item.facilityCategory"
                :value="item.facilityTypeNo"
              />
              <!-- <el-option label="生产设施" value="1" />
              <el-option label="辅助设施" value="2" />-->
            </el-select>
          </el-form-item>

          <el-form-item label="设施编号:" prop="facilityNo" class="w50p">
            <el-input
              v-model="formData.facilityNo"
              :disabled="nowChanceStau==='edit'"
              placeholder="请输入设施编号"
              clearable
            />
          </el-form-item>
          <el-form-item label="设施名称:" prop="facilityName" class="w50p">
            <el-input
              v-model="formData.facilityName"
              :disabled="!canInput"
              placeholder="请输入设施名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="建立时间:" prop="buildTime" class="w50p">
            <el-date-picker
              v-model="formData.buildTime"
              value-format="yyyy-MM-dd"
              placeholder="请输入建立时间"
              clearable
            />
          </el-form-item>
          <el-form-item label="设施面积:" prop="scope" class="w50p">
            <el-input
              v-model="formData.scope"
              placeholder="请输入设施面积"
              :disabled="!canInput"
              clearable
            />
          </el-form-item>
          <el-form-item label="设施单位:" prop="unitNo" class="w50p">
            <el-select
              v-model="formData.unitNo"
              style="width: 100%"
              :disabled="!canInput"
              clearable
              filterable
            >
              <el-option
                v-for="item in unitList"
                :key="item.unitNo"
                :label="item.unitName"
                :value="item.unitNo"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="设施上限:" prop="scope" style="width:50%">
            <el-input
              v-model="formData.facilityQuantity"
              placeholder="请输入设施上限"
              :disabled="!canInput"
              clearable
            />
          </el-form-item>
          <el-form-item label="上限单位:" prop="" style="width:50%">
            <el-select
              v-model="formData.topUnitId"
              style="width: 100%"
              :disabled="!canInput"
              clearable
              filterable
            >
              <el-option
                v-for="item in unitLists"
                :key="item.unitNo"
                :label="item.unitName"
                :value="item.unitNo"
              />
            </el-select>
          </el-form-item>-->
          <el-form-item label="设施造价:" prop="facilityCost" class="w50p">
            <el-input
              v-model.number="formData.facilityCost"
              :disabled="!canInput"
              placeholder="请输入设施造价"
              clearable
            />
          </el-form-item>
          <el-form-item label="设施租金:" prop="facilityRent" class="w50p">
            <el-input
              v-model.number="formData.facilityRent"
              :disabled="!canInput"
              placeholder="请输入设施租金"
              clearable
            />
          </el-form-item>
          <el-form-item label="设施位置:" prop="address" class="w50p">
            <el-input
              v-model="formData.address"
              :disabled="!canInput"
              placeholder="请输入设施位置"
              clearable
            />
          </el-form-item>
          <el-form-item label="经纬度:" prop="axisY" class="w50p axisY">
            <el-col :span="11">
              <el-input v-model="formData.axisY" :disabled="true" />
            </el-col>
            <el-col class="line" :span="2" />
            <el-col :span="11">
              <el-input v-model="formData.axisX" :disabled="true" />
            </el-col>
          </el-form-item>
          <el-form-item label="设施划分:" prop="axisY" class="w50p axisY">
            <el-button :disabled="!canInput" type="primary" @click="openMap">点击按钮进行设施划分</el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="地图绘制"
        class="map-dialog"
        :visible.sync="mapVisible"
        width="80%"
        height="100"
        top="5vh"
        @close="closeMapDialog"
      >
        <baidu-map
          id="map"
          class="map"
          :center="center"
          :zoom="zoom"
          :scroll-wheel-zoom="true"
          map-type="BMAP_HYBRID_MAP"
          @mousemove="syncPolyline"
          @click="paintPolyline"
          @rightclick="newPolyline"
        >
          <bm-control>
            <div class="header_div">
              <div class="paint_btn">
                <el-button
                  type="primary"
                  @click.prevent="toggle('polyline')"
                >{{ polyline.editing ? "停止绘制" : "开始绘制" }}</el-button>
                <el-button type="primary" @click.prevent="cancelCheck">取消选区</el-button>
              </div>
              <div class="search_input">
                <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 999999 }">
                  <el-input
                    v-model="keyword"
                    type="text"
                    placeholder="请输入地名关键字"
                    style="background-color: #003947"
                    clearable
                  >
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                  </el-input>
                </bm-auto-complete>
              </div>
            </div>
          </bm-control>
          <bm-local-search
            :location="''"
            :keyword="keyword"
            :select-first-result="false"
            :auto-viewport="true"
            :panel="false"
            @searchcomplete="searchcomplete"
          />
          <bm-polyline
            v-for="(path, index) in polyline.paths"
            :key="index"
            stroke-color="#f8c901"
            :path="path"
            @lineupdate="openMap"
          />
          <bm-polygon
            v-if="!addActive"
            :path="polygonPath"
            stroke-color="#03F5EC"
            fill-color="#ffdb5c"
            :stroke-opacity="1"
            :stroke-weight="3"
            :fill-opacity="0.7"
            :editing="polyedit"
            @click="!polyedit"
          />
          <bm-marker
            v-for="(item, index) in groupLngLatArr"
            :key="index + 9999999"
            :position="{
              lng: item.center.lng - 0.000003,
              lat: item.center.lat - 0.000043
            }"
            :dragging="false"
          >
            <bm-label
              :content="item[0].title.facilityName"
              :label-style="labelStyle"
              :offset="{ width: -5, height: 15 }"
              @click="infoMultipleOpen(item)"
            />
          </bm-marker>
          <div v-for="(items, indexs) in groupLngLatArr" :key="indexs + 100000">
            <bm-polygon
              :path="items"
              stroke-color="#03F5EC"
              fill-color="#00fff6"
              :stroke-opacity="1"
              :fill-opacity="0.2"
              :stroke-weight="3"
            />
          </div>
        </baidu-map>
        <template #footer>
          <span class="dialog-footer">
            <el-button class="zh-button-one" @click="mapVisible = false">取 消</el-button>
            <el-button class="zh-button-two" type="primary" @click.prevent="confirmSelect">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog
        :title="title"
        class="period-dialog"
        :visible.sync="periodVisible"
        width="80%"
        height="100"
        top="5vh"
        @close="periodVisible = false"
      >
        <el-form>
          <el-form-item label="废弃日期" :required="true">
            <el-date-picker v-model="periodYears" value-format="yyyy-MM-dd" clearable />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button class="zh-button-one" @click="periodDnd">取 消</el-button>
            <el-button class="zh-button-two" type="primary" @click="periodSelect">废 弃</el-button>
          </span>
        </template>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import divideInfoManage from "@/api/digital-operation/land-manage/divide-manage";
import facilityTypeManage from "@/api/basic-info-manage/facility-type-manage";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import UnitManage from "@/api/basic-info-manage/unit-manage";
import agriculturalTypeManage from "@/api/basic-info-manage/agricultural-type-manage";
import SelectButton from "../components/selcetButton/index.vue";
import { mymixin } from "@/utils/mixin";
import { mapGetters } from "vuex";
export default {
  name: "DivideManage",
  components: { SearchForm, ActionBar, Pagination, BaseMainSlot, SelectButton },
  mixins: [mymixin],
  data() {
    var validatefacilityNo = (rule, value, callback) => {
      setTimeout(() => {
        if (!value) {
          callback(new Error("设施编号不能为空！！！"));
        } else {
          var patrn = /[`~!@#$%^&*()\+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）={}|《》？：“”【】、；‘'，。、]/im;
          if (patrn.test(value)) {
            callback(new Error("编号不能包含 $、&、￥等特殊字符"));
            // console.log(value)
            // 如果包含特殊字符返回false
          } else {
            callback();
          }
        }
      }, 20);
    };
    return {
      formConfig: [
        {
          label: '设施类型',
          prop: 'facilityArr',
          type: 'selectbutton',
          options: [], // facilityTypeList
          optionKey: { label: 'facilityCategory' },
        }, {
          label: '承租户',
          prop: 'lesseeNo',
          type: 'select',
          options: [], // lesseeList
          optionKey: { label: 'lesseeName', value: 'lesseeNo' },
        }, {
          label: '设施名称',
          prop: 'facilityName',
          type: 'input',
        }, {
          label: '设施编号',
          prop: 'facilityNo',
          type: 'select',
          options: [], // facilitylist
          optionKey: { label: 'facilityNo', value: 'facilityNo' },
        }, 
      ],
      searchlist: {},
      // 区域是否可修改
      obj: {
        name: ""
      },
      center: { lng: 120.230648, lat: 30.811543 },
      polyline: {
        editing: false,
        paths: []
      },
      polyedit: false,
      // 设施划分 区域 弹出框
      mapVisible: false,
      // 承租户
      // 地图相关值
      zoom: 18,
      lessee: "",
      // 土地名称
      facilityName: "",
      facilityTypeNo: "",
      facilitylist: [],
      topitemtypeid: false,
      // 地图 搜索
      keyword: "",
      // 经纬度数组
      facilityPointList: [],
      // 设施类型
      facilityTypeList: [],
      // 选中的数据项数组 ID组成
      facilityIdList: [],
      // 展示经纬度数组
      polygonPath: [],
      // 农业类型
      Baselist: [],
      // 地图点 label 样式
      labelStyle: {
        color: "#fffff0",
        fontSize: ".75rem",
        borderRadius: ".5rem",
        border: "none",
        backgroundColor: "#00a1c2",
        padding: ".1875rem",
        opacity: ".8",
        letterSpacing: ".125rem",
        transform: "translateX(-32%)"
      },
      // 单位
      unitList: [],
      unitLists: [],
      groupLngLatArr: [],
      lesseeList: [],
      facilityNo: "",
      lesseeNo: "",
      facilityStatus: true,
      // 校验规则
      rules: {
        farmingTypeNo: [
          { required: true, message: "请选择农业类型", trigger: "change" }
        ],
        facilityTypeNo: [
          { required: true, message: "请选择设施类型", trigger: "change" }
        ],
        facilityName: [
          { required: true, message: "请输入设施名称", trigger: "blur" }
        ],
        facilityNo: [
          { required: true, validator: validatefacilityNo, trigger: "blur" }
        ]
      },
      periodYears: "",
      periodVisible: false,
      title: "废弃设施",
      facilityStatusObj: {}
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {
    // // 获取表格数据
    // this.search();
  },
  mounted() {
    this.getBaseList();
  },
  methods: {
    // 获取点击的分页index
    topitemtype(e) {
      this.topitemtypeid = e;
      // 获取表格数据
      this.formData = {};
      this.tableData = [];
      this.facilityName = "";
      // this.lessee = "";
      this.facilityTypeNo = "";
      this.search();
    },
    // 获取表格数据
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sort: "timestamp",
        entity: {
          facilityName: this.searchlist.facilityName || undefined,
          // lessee: this.lessee,
          facilityTypeName: this.searchlist.facilityArr || undefined,
          facilityStatus: this.topitemtypeid,
          facilityNo: this.searchlist.facilityNo || undefined,
          lesseeNo: this.searchlist.lesseeNo || undefined
        }
      };
      divideInfoManage.getDivideList(params).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          // data.content.forEach(item => {
          //   if (item.facilityStatus === 1) {
          //     item.facilityStatus = "1";
          //     // console.log(item.facilityStatus)
          //   } else if (item.facilityStatus === 2) {
          //     item.facilityStatus = "2";
          //     // console.log(item.facilityStatus)
          //   }
          // });
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
      this.polygonPath = [];
    },
    // 下拉框数据
    async getBaseList() {
      // 农业类型
      const { data: res } = await agriculturalTypeManage.ownFarmingTypelist({
        organizationNo: sessionStorage.organizationNo
      });
      this.Baselist = res;
      // 设施类型
      const {
        data: resp
      } = await facilityTypeManage.getfacilityTypeListByCondition();
      this.facilityTypeList = resp;
      this.formConfig[0].options = resp.map(el => {
        return { itemTypeId: el.facilityCategory, itemTypeName: el.facilityCategory }
      })
      // console.log(this.facilityTypeList)
      // 设施单位
      const { data: resa } = await UnitManage.getallBasicunitlist({
        unitTypeNo: "995416636939862016"
      });
      this.unitList = resa;
      const { data: resas } = await UnitManage.getallBasicunitlist({});
      this.unitLists = resas;

      // 获取承租人
      divideInfoManage.queryLessesByCondition().then(res => {
        this.lesseeList = res.data;
        this.formConfig[1].options = res.data;
      });

      let params = {
        facilityStatus: false
      };
      const {
        data: resps
      } = await divideInfoManage.getFacilityListByConditionAll(params);
      this.facilitylist = resps;
      this.formConfig[3].options = resps;
    },
    // 查询所有设施信息
    async FacilPointList() {
      const { data: resp } = await divideInfoManage.queryAllFacilityDetail();
      // let facilityNameArr = resp;
      this.groupLngLatArr = [];
      // this.list = []
      this.list = resp;
      // for (let i = 0; i < facilityNameArr.length; i++) {
      //   const { data: res } = await divideInfoManage.queryFacilityById(facilityNameArr[i].facilityId)
      //   this.list.push(res)
      // }
      let lngLatAll = [];
      this.list.forEach(itemthree => {
        if (itemthree.facilityPointList) {
          let lngLatArr = [];
          let facilityGroupArr = itemthree.facilityPointList;
          facilityGroupArr.forEach(item => {
            const obj = {};
            obj["lng"] = item.axisY;
            obj["lat"] = item.axisX;
            obj["title"] = itemthree;
            lngLatArr.push(obj);
          });
          this.groupLngLatArr.push(lngLatArr);
          this.groupLngLatArr.forEach(item => {
            item["center"] = this.getCenterPoint(item);
          });
          lngLatAll = this.groupLngLatArr[0];
        }
      });
      // setTimeout(() => {
      this.$nextTick(() => {
        if (lngLatAll.length === 0) return;
        this.center = {
          lng: lngLatAll[0].lng,
          lat: lngLatAll[0].lat
        };
        if (this.groupLngLatArr.length > 100) {
          this.zoom = 16;
          this.labelStyle.fontSize = ".75rem";
        } else if (
          this.groupLngLatArr.length > 60 &&
          this.groupLngLatArr.length < 100
        ) {
          this.zoom = 17;
          this.labelStyle.fontSize = ".875rem";
        } else if (
          this.groupLngLatArr.length > 30 &&
          this.groupLngLatArr.length < 60
        ) {
          this.zoom = 18;
          this.labelStyle.fontSize = "1rem";
          this.labelStyle.transform = "translateX(-15%)";
        } else if (this.groupLngLatArr.length < 30) {
          this.zoom = 18;
          this.labelStyle.fontSize = "1.0625rem";
          this.labelStyle.transform = "translateX(0%)";
        }
      });
      // }, 400);
      // console.log(this.list)
    },
    // 计算多边形中心点
    getCenterPoint(data) {
      let lng = 0.0;
      let lat = 0.0;
      for (let point of data) {
        lat += point["lat"];
        lng += point["lng"];
      }
      lng = lng / data.length + 0.000084;
      lat = lat / data.length + 0.000014;
      // console.log(lng, lat);
      return { lng: lng, lat: lat };
    },
    searchcomplete(e) {
      if (e) {
        this.zoom = 18;
        this.center = {
          lat: e.Kr[0].pointN.lat,
          lng: e.Kr[0].pointN.lng
        };
      }
    },
    // table 设施面积添加单位
    unitname(e) {
      let unitName = "";
      this.unitList.forEach(item => {
        if (item.unitNo === e) {
          unitName = item.unitName;
        }
      });
      return unitName;
    },
    farmingType(val) {
      if (this.Baselist) {
        this.Baselist.forEach(item => {
          if (val === item.farmingTypeNo) {
            this.formData.farmingTypeName = item.farmingTypeName;
          }
        });
      }
      // console.log(this.formData)
    },
    facilityCategory(val) {
      if (this.facilityTypeList) {
        this.facilityTypeList.forEach(item => {
          // console.log(item)
          if (val === item.facilityTypeNo) {
            this.formData.facilityTypeName = item.facilityCategory;
          }
        });
      }
      // console.log(this.formData);
    },
    periodDnd() {
      this.periodVisible = false;
      this.search();
    },
    periodSelect() {
      if (this.facilityStatusObj.facilityStatus === true) {
        if (!this.periodYears) {
          return this.$message.warning("请先选择废弃时间！");
        }
        let status = true;
        let params = {
          facilityNo: this.facilityStatusObj.facilityNo,
          facilityStatus: status,
          cancelTime: this.periodYears
        };
        this.divideInfo(params);
      } else if (this.facilityStatusObj.facilityStatus === false) {
        let status = false;
        let params = {
          facilityNo: this.facilityStatusObj.facilityNo,
          facilityStatus: status
        };
        this.divideInfo(params);
      }
      // this.$nextTick(() => {
      //   setTimeout(() => {
      //     this.search();
      //   }, 300);
      // });
    },
    faciStatus(e) {
      this.title = "废弃设施";
      if (this.topitemtypeid === true) {
        this.title = "恢复设施";
        this.$confirm("是否" + this.title, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          customClass: "myClass"
        })
          .then(() => {
            if (e.facilityStatus === true) {
              let status = true;
              let params = {
                facilityNo: e.facilityNo,
                facilityStatus: status
              };
              this.divideInfo(params);
            } else if (e.facilityStatus === false) {
              let status = false;
              let params = {
                facilityNo: e.facilityNo,
                facilityStatus: status
              };
              this.divideInfo(params);
            }
            // this.$nextTick(() => {
            //   setTimeout(() => {
            //     this.search();
            //   }, 300);
            // });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
            this.search();
            // this.resetActionBar();
          });
      } else {
        this.facilityStatusObj = e;
        this.periodVisible = true;
      }
    },
    divideInfo(params) {
      divideInfoManage.editStatus(params).then(res => {
        if (res.code === 1) {
          this.periodYears = "";
          this.facilityStatusObj = {};
          this.periodVisible = false;
          this.search();
          return this.$message.success(res.msg || "修改成功!!!");
        } else return this.$message.warning(res.msg || "修改失败!!!");
      });
    },
    handleClose(done) {
      this.cancel("formData");
      done();
      // this.$confirm("确认关闭？")
      //   .then(_ => {
      //     done();
      //   })
      //   .catch(_ => {});
    },
    // 地图绘制模块
    toggle(name) {
      this[name].editing = !this[name].editing;
    },
    syncPolyline(e) {
      if (!this.polyline.editing) {
        return;
      }
      const { paths } = this.polyline;
      if (!paths.length) {
        return;
      }
      const path = paths[paths.length - 1];
      if (!path.length) {
        return;
      }
      if (path.length === 1) {
        path.push(e.point);
      }
      this.$set(path, path.length - 1, e.point);
    },
    newPolyline(e) {
      if (!this.polyline.editing) {
        return;
      }
      const { paths } = this.polyline;
      if (!paths.length) {
        paths.push([]);
      }
      const path = paths[paths.length - 1];
      path.pop();
      if (path.length) {
        paths.push([]);
      }
    },
    paintPolyline(e) {
      if (!this.polyline.editing) {
        this.formData.axisY = e.point.lng;
        this.formData.axisX = e.point.lat;
        return;
      }
      const { paths } = this.polyline;
      !paths.length && paths.push([]);
      paths[paths.length - 1].push(e.point);
    },
    // 打开地图dialog
    openMap() {
      this.mapVisible = true;
      this.FacilPointList();
    },
    // 关闭地图dialog
    closeMapDialog() {
      this.polygonPath = [];
      this.polyline.paths = [];
      this.polyline.editing = false;
      this.center = { lng: 120.230648, lat: 30.811543 };
    },
    // 取消选取
    cancelCheck() {
      this.polyline.paths = [];
      this.polygonPath = [];
    },
    // 确认选取
    confirmSelect() {
      this.facilityPointList = [];
      this.mapVisible = false;
      this.polyline.paths[0].forEach((item, index) => {
        if (index == this.polyline.paths[0].length - 1) return
        const obj = {};
        obj["axisX"] = item.lat;
        obj["axisY"] = item.lng;
        obj["sort"] = index;
        obj["type"] = 0; // 0地图， 1图片
        this.facilityPointList.push(obj);
      });
    },
    // 初始化操作栏状态
    resetActionBar() {
      // this.$refs["formData"].resetFields();
      this.$refs["tableData"].clearSelection();
      this.keyword = "";
      this.facilityPointList = [];
      this.polyline = {
        editing: false,
        paths: []
      };
      this.canInput = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
    },
    // 搜索
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // 点击行时
    handleEdit(row) {
      this.titleText = "修改";
      let facilityNo = row.facilityNo;
      // TODO 点击行元素后 edit
      // this.queryFaciliy();
      if (!this.topitemtypeid) {
        this.formData = JSON.parse(JSON.stringify(row));
        let obj = this.facilityTypeList.find(
          el => el.facilityCategory === this.formData.facilityTypeName
        );
        if (obj) this.formData.facilityTypeNo = obj.facilityTypeNo;
        this.polygonPath = [];
        if (facilityNo) {
          divideInfoManage.queryFacilityById(facilityNo).then(res => {
            let data = res.data;
            this.facilityPointList = data.facilityPointList;
            if (this.facilityPointList) {
              this.facilityPointList.forEach(item => {
                const obj = {};
                obj["lng"] = item.axisY;
                obj["lat"] = item.axisX;
                this.polygonPath.push(obj);
              });
              this.center = {
                lng: this.polygonPath[0].lng,
                lat: this.polygonPath[0].lat
              };
            }
          });
        }
        this.editActive = true;
        this.saveActive = false;
        this.cancelActive = false;
        this.canInput = true;
        this.qrActive = true;
        this.nowChanceStau = "edit";
        this.dialogFormVisible = true;
      } else {
        // this.$message.warning('历史设施不允许修改!!!')
      }
    },
    handleSelectionChange(list) {
      this.facilityIdList = [];
      this.facilityIdList = list.map(item => item.facilityNo);
      if (this.topitemtypeid === 1) {
        this.delActive = this.facilityIdList.length > 0;
      } else {
        this.$message.warning("历史设施不允许删除!!!");
      }
    },
    // 添加
    add() {
      this.canInput = true;
      this.nowChanceStau = "add";
      if (this.Baselist !== undefined && this.Baselist.length === 1) {
        this.formData = {
          farmingTypeNo: this.Baselist[0].farmingTypeNo,
          farmingTypeName: this.Baselist[0].farmingTypeName
          // facilityTypeNo: 2
        };
      }
      this.titleText = "添加";
      this.dialogFormVisible = true;
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false;
    },
    delmessage() {
      divideInfoManage.delDivideInfo(this.facilityIdList).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.search();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    handleDelete(row) {
      divideInfoManage.delDivideInfo([row.facilityNo]).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.search();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // this.formData.organizationNo = sessionStorage.organizationNo;
            this.formData["facilityPointList"] = this.facilityPointList;
            // delete this.formData.facilityName;
            divideInfoManage.editDivideInfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.formData = {};
                this.$refs[formData].resetFields();
                this.search();
                this.dialogFormVisible = false;
              } else {
                this.$message.error(res.msg || "修改失败！");
                this.canInput = true;
              }
            });
          } else if (this.nowChanceStau === "add") {
            this.formData["facilityPointList"] = this.facilityPointList;
            this.facilityCategory(this.formData.facilityTypeNo);
            this.formData.organizationNo = sessionStorage.organizationNo;
            divideInfoManage.addDivideInfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.formData = {};
                this.$refs[formData].resetFields();
                this.search();
                this.dialogFormVisible = false;
              } else {
                this.$message.error(res.msg || "新增失败！");
                this.canInput = true;
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
.pag {
  height: 100%;
  width: 100%;
  border: .0625rem dashed rgba(14, 196, 151, 1);
  position: relative;
  padding: 1rem 1.25rem 0;
}
::v-deep .common-layout {
  .zhcontent {
    margin-bottom: 0 !important;
    height: calc(100% - 1.25rem) !important;
    .pagination {
      right: 1.25rem !important;
    }
  }
}
::v-deep .el-form-item__content {
  display: flex;
  align-items: center;
}
.formData {
  ::v-deep .el-dialog {
    .el-dialog__body {
      height: 80%;
      overflow-y: auto;
      .el-form {
        height: 100%;
        display: flex;
        flex-wrap: wrap;
        overflow-y: auto;
      }
    }
  }
}
.dialog {
  ::v-deep .el-dialog__title {
    font-weight: bold;
  }
  .qrCode {
    // color: #00fff6;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.common-layout {
  border: .0625rem solid $borderColor;
  height: calc(100% - #{$actionBarHeight + 10});
  padding: 1.25rem;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  .wrap,
  .search-box {
    width: 100%;
  }
  .wrap {
    display: flex;
    height: calc(100% - 2.25rem - 1.25rem);
  }
  ::v-deep .axisY .el-form-item__content {
    justify-content: space-between;
    &::after,
    &::before {
      display: none;
    }
    .el-input {
      width: 45%;
    }
  }
}
.map {
  width: 100%;
  height: 100%;
  .BMap_noprint {
    width: 100%;
    .header_div {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
::v-deep .map-dialog {
  .el-dialog {
    width: 80vw !important;
    height: 90vh !important;
  }
}
::v-deep .period-dialog {
  .el-dialog {
    width: 22vw !important;
    height: 22vh !important;
    margin-top: 15vh !important;
    min-width: 18.75rem;
    .el-dialog__body {
      height: 10vh;
      overflow: hidden;
    }
  }
}

::v-deep .el-form-item.is-error {
  .el-input__inner {
    border-color: #f56c6c !important;
  }
}
// 隐藏 地图点
// ::v-deep .BMap_Marker {
//   div {
//     display: none;
//   }
// }
// ::v-deep .BMap_noprint {
//   display: none;
// }
::v-deep .map {
  > div:first-child {
    > div:first-child {
      > div:nth-child(2) {
        div:nth-last-child(3) {
          display: none;
        }
      }
    }
  }
}
</style>
